﻿using Student.Common;
using Student.DAL;
using Student.Model;
using Newtonsoft.Json;
using System.Data;
using Student.ViewModel;

namespace Student.BLL
{
    public class UserTokenBO
    {
        private readonly UserDAO userDAO = new();
        private readonly UserTokenDAO _userTokenDAO;
        private const string PreUserTokenKey = "UserToken:";
        private readonly int InvalidDays = 5;

        public UserTokenBO()
        {
            _userTokenDAO = new UserTokenDAO();
        }

        public UserTokenBO(UserTokenDAO userTokenDAO)
        {
            _userTokenDAO = userTokenDAO;
        }

        public bool ValidToken(string token)
        {
            if (string.IsNullOrEmpty(token))
                return false;

            bool result = false;
            var userToken = GetInfoByToken(token);
            if (userToken != null && userToken.ExpiredTime > DateTime.Now)
            {
                result = true;
            }

            return result;
        }

        public UserTokenViewModel GetUserTokenViewModelByToken(string token)
        {
            var ut = GetInfoByToken(token);
            var utv = new UserTokenViewModel
            {
                UserDataID = ut?.UserDataID ?? 0,
                FullName = "",
                RoleLevel = 0,
            };

            var user = userDAO.GetUser(ut?.UserDataID ?? 0);
            if (user == null) return utv;
            return utv;
        }

        public UserToken? GetInfoByToken(string token)
        {
            UserToken? userToken = null;

            userToken = _userTokenDAO.GetInfoByToken(token);

            return userToken;
        }

        public string InsertUserToken(int userDataID, int userClient, IDbTransaction? trans = null)
        {
            //新增Token
            string token = Guid.NewGuid().ToString("N");
            var userToken = new UserToken()
            {
                UserDataID = userDataID,
                Token = token,
                CreateTime = DateTime.Now,
                ExpiredTime = DateTime.Now.AddDays(InvalidDays)
            };

            var list = _userTokenDAO.GetEffectiveList(userDataID, userClient, trans);
            var editTime = DateTime.Now.AddDays(-InvalidDays).AddMinutes(3);
            if (list != null)
            {
                foreach (var info in list)
                {
                    if (info.ExpiredTime > editTime)
                    {
                        info.ExpiredTime = editTime;
                    }
                }

                _userTokenDAO.Update(list, trans);
            }
            var rows = _userTokenDAO.Insert(userToken, trans);

            if (rows <= 0)
                return "";

            return token;
        }      
    }
}